#!/usr/bin/env python

import csv
import urllib
import os.path
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
#Load validation (non-binding) data from files
#into usable form
#Chen's paper
#pdz-domain sequence and

def GetProteinFile(acc):
    #Ensemble peptide accs have been manually mapped to Uniprot Acc
    if acc.startswith('UPI'):
        #uniparc file
        try:
            f = urllib.urlretrieve('http://www.uniprot.org/uniparc/'+acc+'.fasta', 'validate_data/proteins/'+acc+'.fasta')
        except:
            #print e
            return False
    elif acc.startswith('ENSMUSP'):
        #Ensemble peptide accs have been manually mapped to Uniprot Acc
        pass    
    else:
        try:
            f = urllib.urlretrieve('http://www.uniprot.org/uniprot/'+acc+'.fasta', 'validate_data/proteins/'+acc+'.fasta')
        except:
            #print e
            return False
    return True

def parse_domain(domain, acc, start, end):
    #load acc file and parse into domain accroding to start, end
    seq_record = SeqIO.parse("validate_data/proteins/"+acc+".fasta", "fasta").next()
    # output domain
    d = seq_record[(start-1):(end-1)]
    tmpFile = open('validate_data/domains/'+domain+'.fasta', 'w')
    SeqIO.write(d, tmpFile, "fasta")
    tmpFile.close()
    return True

def read_interaction_file(fname, pep):
    #First column is the PDZ domain
    #rest columns are the scores for the peptides
    #0, -1 = negative binding, >0 = positive binding

    inter = dict()
    with open(fname, 'rb') as csvfile:
         spamreader = csv.reader(csvfile)
         for row in spamreader:
            pdzdomain = row[0]
            #last column of pep is '' <-- empty, so len(pep) -1
            for i in range(len(pep)-1):
                inter[pdzdomain, pep[i]] = float(row[i+1])
    return inter        
            
            
def read_domain_file(fname):
    with open(fname, 'rb') as csvfile:
        spamreader = csv.reader(csvfile)
        for row in spamreader:
            domain = row[0]
            acc = row[1]
            start,end = row[2].split('-')
            #print domain, acc, int(start), int(end)
            if os.path.exists('validate_data/proteins/'+acc+'.fasta'):
                #if the domain has been parsed
                if os.path.exists('validate_data/domains/'+domain+'.fasta'):
                    pass
                else:
                    #parse the domain
                    parse_domain(domain, acc, int(start), int(end))
                    print domain, 'created.'
            else:
                #download file from uniprot, if not found
                if GetProteinFile(acc) is True:
                    print acc, "downloaded."
                else:
                    print "ERROR"
    return

def read_peptide_file(fname):
    
    peptides = []
    with open(fname, 'rb') as csvfile:
         spamreader = csv.reader(csvfile)
         for row in spamreader:
            name = row[0]
            seq = row[1]
            peptides.append(seq)
            
    return peptides
    

if __name__ == '__main__':
    print "Starting..."
    #create fasta file for each PDZ domain
    read_domain_file('validate_data/pdzdomains.csv')
    
    #
    pep = read_peptide_file('validate_data/validation_peptides.csv')
    
    inter = read_interaction_file('validate_data/interactions.csv', pep)
    
    for i in inter:
        if inter[i] > 0:
            bind = True
        else:
            bind = False
            
        print i, inter[i], bind
